package nil.ed.simulator.request.output.impl;

import nil.ed.simulator.request.common.QQItem;
import nil.ed.simulator.request.output.IOutput;
import nil.ed.simulator.request.repo.RuntimeRepo;

import java.io.File;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lidelin.
 */
public class CookieOutput implements IOutput {

    private static final String DEM = "----";

    @Override
    public void output(File file) throws Exception {
        try (OutputStream outputStream = Files.newOutputStream(Paths.get(file.getAbsolutePath()), StandardOpenOption.CREATE_NEW)) {
            List<QQItem> itemList = RuntimeRepo.QQ_REPO.getQqList();
            List<QQItem> copied = new LinkedList<>(itemList);
            StringBuilder builder = new StringBuilder();
            for (QQItem qqItem : copied) {
                builder.append(qqItem.getQq()).append(DEM).append(qqItem.getPassword()).append(DEM);
                if (qqItem.getCookies() == null) {
                    builder.append("Unknown");
                } else {
                    String cookieStr = qqItem.getCookies().stream().map(nv -> String.format("%s=%s", nv.getName(), nv.getValue())).collect(Collectors.joining("; "));
                    builder.append(cookieStr);
                }
                builder.append("\n");
            }
            outputStream.write(builder.toString().getBytes(StandardCharsets.UTF_8));
        }
    }
}
